#include "File.h"
#include "IData.h"
#include <fstream>
#include <iostream>
#include <cstdlib>

using namespace std;

//Constructor. Takes a filename and an IData pointer. If no 
//filename is assisiated it will use the default filename.
File::File(char* _fileName)
{
	if(_fileName != NULL && _fileName != "")
		fileName = _fileName;
	else
		fileName = "savedDataCollection.txt";
}


File::~File(void)
{
}

//Get will retrieve the specific data (from id) from 
//the file and return it as an IData pointer.
bool File::get(char* id, IData* data)
{
	bool isset = false;
	ifstream file;
	file.open(fileName);

	if(file.is_open())
	{
		char current = ' ';
		string tmp = "";

		while(!file.eof())
		{
			current = file.get();

			if(current == recordSeparator)
			{
				char* testData = const_cast<char*>(tmp.c_str());

				if(data->compareId(id, testData, unitSeparator))
				{
					data->set(testData, unitSeparator);
					isset = true;
				}

				tmp = "";
			}

			else
			{
				tmp += current;
			}
		}
	}

	file.close();

	if(data->isValid() && isset)
		return true;
	return false;
}

//Set converts the IData data to a string which gets persisted in a file.
//Returns true if it succeeded.
bool File::set(IData* _data)
{
	string dataCode = _data->toString(unitSeparator);

	if(dataCode != "")
	{
		ofstream file;
		file.open(fileName, ios::out | ios::app);

		if(file.is_open())
		{
			file << dataCode << recordSeparator;
			file.close();

			if(!file.is_open())
				return true;
		}
	}
	
	return false;
}